package cn.cxy.customviewdemos

import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.View

/**
 * 三角形
 */
class TriangleView2(context: Context, attrs: AttributeSet?) : View(context, attrs) {
    private val mPaint = Paint()
    private val intervalTime = 50 //重绘间隔时间
    private val path = Path()
    private var isIncreasing = false //当前是否处于放大过程中
    private var percentValue = 100 //缩放比例

    init {
        //设置实心
        mPaint.style = Paint.Style.FILL
        //设置颜色
        mPaint.color = Color.BLUE
        // 设置画笔的锯齿效果
        mPaint.isAntiAlias = true
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        drawTriangle(canvas)
    }

    private fun drawTriangle(canvas: Canvas) {
        path.reset()
        val percent = percentValue.toFloat() / 100
        path.moveTo(width.toFloat() * percent / 2, 0f)
        path.lineTo(width.toFloat() * percent, height.toFloat() * percent)
        path.lineTo(0f, height.toFloat() * percent)
        path.close()
        canvas.drawPath(path, mPaint)
        // 隔一段时间重绘一次, 动画效果
        handler.postDelayed(runnable, intervalTime.toLong())
    }

    // 重绘线程
    private val runnable = Runnable {
        smoothChangeRadiusSize()
        invalidate()
    }

    /**
     * 先缩小，后放大，营造呼吸效果
     */
    private fun smoothChangeRadiusSize() {
        if (isIncreasing) {
            percentValue++
        } else {
            percentValue--
        }
        if (percentValue <= 0) {
            percentValue++
            isIncreasing = true
        } else if (percentValue >= 100) {
            percentValue--
            isIncreasing = false
        }
    }
}